import type { SelectProps } from 'antd';
import { Flex, Select } from 'antd';
import { useEffect, useRef, useState } from 'react';
import TemplateContainer from '@/components/Template/TemplateContainer';
import { modulesData } from '@/pages/template/constants';
import type { DragItemType } from '@/types/template';

const RenderTemplate: React.FC = () => {
  const templateData = useRef<Record<string, DragItemType[]>>({});
  const [templateOptions, setTemplateOptions] = useState<
    SelectProps['options']
  >([]);
  const [selectedTemplate, setSelectedTemplate] = useState<DragItemType[]>([]);
  const getTemplateList = async () => {
    const data = JSON.parse(localStorage.getItem('templateData') || '{}');
    templateData.current = data;
    const options = Object.keys(data).map((key) => ({
      label: key,
      value: key,
    }));
    setTemplateOptions(options);
  };
  const handleSelectChange = (value: string) => {
    if (!value) {
      setSelectedTemplate([]);
      return;
    }
    const template = templateData.current[value];
    const templateForData = template.map((item) => ({
      ...item,
      value: modulesData[item.field as keyof typeof modulesData] || '',
    }));
    setSelectedTemplate(templateForData);
  };
  useEffect(() => {
    getTemplateList();
  }, []);
  return (
    <>
      <Flex gap="small" wrap style={{ marginBottom: '20px' }}>
        <Select
          allowClear
          showSearch
          style={{ width: 200 }}
          placeholder="请选择模板"
          options={templateOptions}
          onChange={handleSelectChange}
        />
      </Flex>
      <TemplateContainer
        type="render"
        template={selectedTemplate}
        dataSource={modulesData}
      />
    </>
  );
};
export default RenderTemplate;
